﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using System.Net.Http.Headers;

namespace FeiCheLiPeiTestTool
{
    public partial class RequestContentForm : Form
    {
        public RequestContentForm()
        {
            InitializeComponent();
        }

        public List<RequestContentModel> _contentLists = new List<RequestContentModel>();

        public string _currentUrlOfParrent = string.Empty;

        FileSystemWatcher fw;
        WatcherTimer _WatcherTimer;

        private void RequestContentForm_Load(object sender, EventArgs e)
        {
            //从文件中加载保单号
            LoadPolicyNos();
            //从文件中加载报案号
            LoadRegisterNos();
            //从文件中加载人保账号
            LoadAccounts();


            //加载已经添加的请求内容
            InitContentForListBox();
            //接口名 comboBox数据绑定
            InitComboBox1Data();
            //文件侦听
            FileDoTask();

            AccountTxtMonitor();
            this.listBox2.HorizontalScrollbar = true;
            this.listBox3.HorizontalScrollbar = true;
            this.listBox4.HorizontalScrollbar = true;


        }

        /// <summary>
        /// 从配置文件中读取接口名称
        /// </summary>
        /// <returns></returns>
        public string[] GetInterfaces()
        {
            var list = new List<string>();
            using (FileStream fs = new FileStream(@"interfaceConfig.txt", FileMode.Open))
            {
                using (StreamReader reader = new StreamReader(fs,Encoding.UTF8))
                {

                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        list.Add(line);
                    }
                }
            }
            return list.ToArray();
        }

        private void InitComboBox1Data()
        {
            var strList = GetInterfaces();

            if (!string.IsNullOrWhiteSpace(_currentUrlOfParrent) && strList != null && _currentUrlOfParrent.ToLower().Contains("database"))
            {
                //线上库查询
                strList = strList.Where(x => x.ToLower().Contains("query")).ToArray();

            }
            else if (!string.IsNullOrWhiteSpace(_currentUrlOfParrent) && strList != null && _currentUrlOfParrent.ToLower().Contains("15002"))
            {
                //使用线上账号抓取数据
                strList = strList.Where(x => x.ToLower().Contains("线上账号")).ToArray();

            }
            else if (!string.IsNullOrWhiteSpace(_currentUrlOfParrent) && strList != null && _currentUrlOfParrent.ToLower().Contains("15001")
                && !_currentUrlOfParrent.Contains("127.0.0"))
            {
                //使用线下账号抓取数据
                strList = strList.Where(x => !x.ToLower().Contains("线上账号") && !x.ToLower().Contains("query")).ToArray();

            }
            comboBox1.Items.AddRange(strList);



        }
        //从文件中加载保单号
        private void LoadPolicyNos()
        {
            //文件是否存在
            if (!Directory.Exists(@".\RegisterNoAndPolicyNo"))
            {
                Directory.CreateDirectory(@".\RegisterNoAndPolicyNo");
            }
            if (!File.Exists(@".\RegisterNoAndPolicyNo\policyNo.txt"))
            {
                File.Create(@".\RegisterNoAndPolicyNo\policyNo.txt");
            }
            else
            {
                using (FileStream fs = new FileStream(@".\RegisterNoAndPolicyNo\policyNo.txt", FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                    {
                        string fileInfo = string.Empty;
                        while (true)
                        {
                            fileInfo = sr.ReadLine();
                            if (fileInfo == null)
                            {
                                break;
                            }

                            if (this.IsHandleCreated)
                            {
                                this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 1, fileInfo, this.listBox2 });
                            }

                            System.Threading.Thread.Sleep(1);
                        }
                    }
                }
            }
        }

        //从文件中加载报案号
        private void LoadRegisterNos()
        {
            try
            {
                //文件是否存在
                if (!Directory.Exists(@".\RegisterNoAndPolicyNo"))
                {
                    Directory.CreateDirectory(@".\RegisterNoAndPolicyNo");
                }
                if (!File.Exists(@".\RegisterNoAndPolicyNo\registerNo.txt"))
                {
                    File.Create(@".\RegisterNoAndPolicyNo\registerNo.txt");
                }
                else
                {
                    using (FileStream fs = new FileStream(@".\RegisterNoAndPolicyNo\registerNo.txt", FileMode.Open))
                    {
                        using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                        {

                            string fileInfo = string.Empty;
                            while (true)
                            {
                                fileInfo = sr.ReadLine();
                                if (fileInfo == null)
                                {
                                    break;
                                }

                                if (this.IsHandleCreated)
                                {
                                    this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 1, fileInfo, this.listBox3 });
                                }

                                System.Threading.Thread.Sleep(1);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                //调度后这里会报异常，，
            }
        }

        //从文件中加载人保系统帐号
        private void LoadAccounts()
        {
            //文件是否存在
            if (!Directory.Exists(@".\Account"))
            {
                Directory.CreateDirectory(@".\Account");
            }
            if (!File.Exists(@".\Account\account.txt"))
            {
                File.Create(@".\Account\account.txt");
            }
            else
            {
                using (FileStream fs = new FileStream(@".\Account\account.txt", FileMode.Open))
                {
                    using (var reader = new StreamReader(fs, Encoding.Default))
                    {
                        string fileInfo = string.Empty;
                        while (true)
                        {
                            fileInfo = reader.ReadLine();
                            if (fileInfo == null)
                            {
                                break;
                            }

                            if (this.IsHandleCreated)
                            {
                                this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 1, fileInfo, this.listBox4});
                            }

                            System.Threading.Thread.Sleep(1);
                        }
                    }
                }
            }
        }

        //加载已经添加的请求内容
        private void InitContentForListBox()
        {
            foreach (var item in _contentLists)
            {
                this.listBox1.Items.Add(item.MethodName + "=" + item.RequestContent);
            }
        }

        //文件侦听
        private void FileDoTask()
        {
            try
            {
                fw = new FileSystemWatcher(@".\RegisterNoAndPolicyNo", "*.txt")
                {
                    EnableRaisingEvents = true,
                    NotifyFilter = NotifyFilters.LastWrite
                };
                _WatcherTimer = new WatcherTimer(OnFileChanged, 1000);
                fw.Changed += _WatcherTimer.OnFileChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //文件侦听
        private void AccountTxtMonitor()
        {
            try
            {
                fw = new FileSystemWatcher(@".\Account", "*.txt")
                {
                    EnableRaisingEvents = true,
                    NotifyFilter = NotifyFilters.LastWrite
                };
                _WatcherTimer = new WatcherTimer(OnFileChanged, 1000);
                fw.Changed += _WatcherTimer.OnFileChanged;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //文件变动事件
        private void OnFileChanged(object sender, FileSystemEventArgs e)
        {
            if (e.Name == "registerNo.txt")
            {
                if (this.IsHandleCreated)
                {
                    this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 0, "", this.listBox3 });
                }

                LoadRegisterNos();
            }
            else if (e.Name == "policyNo.txt")
            {
                if (this.IsHandleCreated)
                {
                    this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 0, "", this.listBox2 });
                }

                LoadPolicyNos();
            }
            else if (e.Name == "account.txt")
            {
                if (this.IsHandleCreated)
                {
                    this.BeginInvoke(new SetListBoxInfoDelegate(SetListBoxInfo), new object[] { 0, "", this.listBox4 });
                }

                LoadAccounts();

            }
        }

        //获取模板文件信息
        private string GetModelInfo(string path)
        {
            string result = string.Empty;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                using (StreamReader sr = new StreamReader(fs, Encoding.Default))
                {
                    result = sr.ReadToEnd();
                }
            }
            return result;
        }

        //打开报案号文件导入新的报案号
        private void button6_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe", @".\RegisterNoAndPolicyNo\registerNo.txt");
        }

        //打开保单号文件导入新的保单号
        private void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe", @".\RegisterNoAndPolicyNo\policyNo.txt");
        }

        private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex < 0 || string.IsNullOrEmpty(this.richTextBox1.Text))
            {
                return;
            }

            var jcontent = JObject.Parse(this.richTextBox1.Text);

            if (jcontent["RegistNo"] != null)
            {
                jcontent["RegistNo"] = this.listBox3.SelectedItem.ToString().Split('=')[0];
            }
            if (jcontent["registNo"] != null)
            {
                jcontent["registNo"] = this.listBox3.SelectedItem.ToString().Split('=')[0];
            }

            if (jcontent["TaskId"] != null)
            {
                jcontent["TaskId"] = this.listBox3.SelectedItem.ToString().Split('=')[1];
            }
            if (jcontent["taskId"] != null)
            {
                jcontent["taskId"] = this.listBox3.SelectedItem.ToString().Split('=')[1];
            }
            this.richTextBox1.Text = jcontent.ToString();
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex < 0 || string.IsNullOrEmpty(this.richTextBox1.Text))
            {
                return;
            }

            var jcontent = JObject.Parse(this.richTextBox1.Text);

            if (jcontent["Content"] != null)
            {
                jcontent["Content"] = this.listBox2.SelectedItem.ToString().Split('=')[0];
            }

            if (jcontent["QueryContent"] != null)
            {
                jcontent["QueryContent"] = this.listBox2.SelectedItem.ToString().Split('=')[0];
            }

            if (jcontent["PolicyNo"] != null)
            {
                jcontent["PolicyNo"] = this.listBox2.SelectedItem.ToString().Split('=')[0];
            }

            if (jcontent["PayeeName"] != null)
            {
                jcontent["PayeeName"] = this.listBox2.SelectedItem.ToString().Split('=')[1];
            }

            this.richTextBox1.Text = jcontent.ToString();
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.listBox1.SelectedIndex > -1)
            {
                this.richTextBox1.Text = JObject.Parse(_contentLists[this.listBox1.SelectedIndex].RequestContent).ToString();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.richTextBox1.Text))
            {
                return;
            }
            RequestContentModel rcm = new RequestContentModel();
            rcm.MethodName = this.comboBox1.Text.Split('-')[0];
            rcm.RequestContent = this.richTextBox1.Text;
            rcm.IsSync = false;
            _contentLists.Add(rcm);

            this.listBox1.Items.Add(rcm.MethodName + "=" + rcm.RequestContent);
        }

        private void button4_Click(object sender, EventArgs e)
        {
            int index = this.listBox1.SelectedIndex;
            if (index > -1)
            {
                _contentLists.RemoveAt(index);
                this.listBox1.Items.RemoveAt(index);
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        delegate void SetListBoxInfoDelegate(int type, string info, ListBox lb);

        void SetListBoxInfo(int type, string info, ListBox lb)
        {
            if (type == 0)
            {
                lb.Items.Clear();
            }
            else
            {
                lb.Items.Add(info);
            }
        }

        private void RequestContentForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            fw.Changed -= _WatcherTimer.OnFileChanged;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBox1.SelectedIndex > -1)
            {
                if (File.Exists(@".\ModelFiles\" + comboBox1.Text.Split('-')[0] + ".txt"))
                {
                    this.richTextBox1.Text = JObject.Parse(GetModelInfo(@".\ModelFiles\" + comboBox1.Text.Split('-')[0] + ".txt")).ToString();
                }
            }
        }

        /// <summary>
        ///  //打开人保账号文件导入账号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void button2_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("notepad.exe", @".\Account\account.txt");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox4_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 更换登录账户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            try
            {
                if (listBox4.SelectedIndex < 0 || string.IsNullOrEmpty(this.richTextBox1.Text))
                {
                    return;
                }

                var jcontent = JObject.Parse(this.richTextBox1.Text);



                if (jcontent["LoginParam"] != null)
                {
                    var jobj = jcontent["LoginParam"];
                    if (jobj["UserName"] != null)
                    {
                        jobj["UserName"] = this.listBox4.SelectedItem.ToString().Split('=')[1].Split('=')[0];
                    }

                    if (jobj["Password"] != null)
                    {
                        jobj["Password"] = this.listBox4.SelectedItem.ToString().Split('=')[2].Split('=')[0];
                    }
                }
                this.richTextBox1.Text = jcontent.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("检查账号文件配置格式应为： 账户名=1234=password=权限：XXX");
            }
        }

        /// <summary>
        /// 提交调度给谁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {

            try
            {
                if (listBox4.SelectedIndex < 0 || string.IsNullOrEmpty(this.richTextBox1.Text))
                {
                    return;
                }

                var jcontent = JObject.Parse(this.richTextBox1.Text);

                if (jcontent["ToName"] != null)
                {
                    jcontent["ToName"] = this.listBox4.SelectedItem.ToString().Split('=')[0];
                }
                if (jcontent["ToCode"] != null)
                {
                    jcontent["ToCode"] = this.listBox4.SelectedItem.ToString().Split('=')[1].Split('=')[0];
                }
                //简易立案，立案
                if (jcontent["UserCode"] != null)
                {
                    jcontent["UserCodeName"] = this.listBox4.SelectedItem.ToString().Split('=')[0];
                }
                if (jcontent["UserCodeName"] != null)
                {
                    jcontent["UserCode"] = this.listBox4.SelectedItem.ToString().Split('=')[1].Split('=')[0];
                }
                this.richTextBox1.Text = jcontent.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show("检查账号文件配置格式应为： 账户名=1234=password=权限：XXX");
            }

        }
    }
}